package cungdeal_controller.interceptors.basic_function_inter;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import model.dap.dao.ConsumerDAO;
import model.dap.domain.Consumer;
import model.dap.mapper.ConsumerMapper;

import org.apache.struts2.ServletActionContext;
import org.apache.struts2.interceptor.SessionAware;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.ValidationAware;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;
import common.base.BaseAction;
import common.util.Consts;

public class LoginMasterInterceptor extends AbstractInterceptor implements SessionAware{
	private static final long serialVersionUID = 1L;
	public void init() {}
	public void destroy () {}

	private Map<String, Object> _session;
	@Override
	public void setSession(Map<String, Object> session) {
		_session = session;
	}
	
	
	public String intercept(ActionInvocation invocation) throws Exception {

		ConsumerMapper consumerMapper = new ConsumerDAO();
		HttpServletRequest request = ServletActionContext.getRequest();
		if(request.getParameter("nextPage")!=null){
			BaseAction.setNextPage(request.getParameter("nextPage"));
		}
		if(request.getParameter("dealID")!=null){
			BaseAction.setSelectedDealID(Integer.parseInt(request.getParameter("dealID")));
		}
		_session = ActionContext.getContext().getSession();
		Consumer consumer  = (Consumer)_session.get(Consts.SESSION_LOING_MASTER_USER);
		if ( consumer != null ){
			Consumer consumer_result = consumerMapper.login(consumer);

			if ( null != consumer_result && consumer.getPassWord().equals(consumer_result.getPassWord()) ){
				return invocation.invoke();
			} else {
				if ( invocation.getAction() instanceof ValidationAware){
					((ValidationAware) invocation.getAction()).addActionError( "userid ã�¾ã�Ÿã�¯ password ã�Œé�•ã�„ã�¾ã�™ã€‚");
				}
				return "master_login";
			}
		} 
		//Danh cho Android
		else {
			 String userId = request.getParameter("user_id");
			 String password = request.getParameter("password");
				 if(userId==null||password == null){
					 return "master_login";
				 }
	
				 consumer=new Consumer();
				 consumer.setUserID(userId);
				 consumer.setPassWord(password);
	
				Consumer user_result = consumerMapper.login(consumer);
				if(user_result !=null){
					_session.put(Consts.SESSION_LOING_MASTER_USER, user_result);
					return invocation.invoke();
				}
				return "master_login";
		}
			 
	}
}
